package com.zzxx.exam.entity;

import com.zzxx.exam.util.Config;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 实体数据管理, 用来读取数据文件放到内存集合当中
 */
public class EntityContext {
    /**
     * 解析配置文件信息：
     *
     *  用户解析
     *
     *  试卷解析
     *
     *  考试规则解析
     */
    //用户集合
    Map<Integer, User> userMap = new HashMap<>();
    //题目组，将其进行分级存储
    HashMap[] questionsMap = new HashMap[10];  //带有唯一 id 的题目集(有id，不好随机获取题
//    ArrayList[] questionsList = new ArrayList[10];  //不带 id 的，可能会重复的题，但可以通过id排除重复（主要是好随机拿题
    HashMap<Integer, ArrayList<Question>> questionList = new HashMap<>();
    //题目唯一标识 id
    private static int ids;
    //考试规则
    String rule;
    //配置文件
    Config config;

    public EntityContext(){
        //创建即加载数据
        for (int i = 0; i < 10; i++) {
            questionList.put(i + 1, new ArrayList<>());
        }
        config = new Config("client.properties");

        getAllUser();  //通过
        getAllQuestion();  //通过
        getRule();

    }

    //从文件获取所有用户数据
    private void getAllUser() {
//        String userPath = "src/com/zzxx/exam/util/user.txt";
//        String userPath = properties.getProperty("UserFile");
        String userPath = config.getString("UserFile");
        BufferedReader userReader;
        try {
            userReader = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(userPath))));
            //打包成对象，存到集合中
            String user;
            while ((user = userReader.readLine()) != null){
                //考虑空格
                user = user.replaceAll(" ","");  //别用trim(),因为它只去掉两头的空格

                if (user.length() != 0 && user.split(":")[0].matches("\\d+")){
                    String[] mes = user.split(":");
                    User u = new User(mes[1], Integer.parseInt(mes[0]), mes[2]);
                    u.setEmail(mes[mes.length - 1]);
                    u.setPhone(mes[3]);
                    userMap.put(u.getId(), u);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //从文件获取所有题目数据,每道题有唯一标识 id
    private void getAllQuestion() {
        String questionPath = config.getString("QuestionFile");
        BufferedReader questionReader;
        //打包成题目，存到题目集合中
        try {
            questionReader = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(questionPath))));
            String str;
            //拆解获取到到字符串
            //优化版正则："[@,][a-z]+="
            while ((str = questionReader.readLine()) != null && str.matches("@answer=[\\d/]+,score=\\d+,level=\\d+")){
                String[] mes = str.split(",");
                Question question = new Question();
                String[] ansPre = mes[0].split("=");
                String[] answers = ansPre[1].split("/");
                //答案、分数、等级
                for (String s : answers){
                    question.getAnswers().add(Integer.parseInt(s));
                }
                question.setScore(Integer.parseInt(mes[1].split("=")[1]));
                question.setLevel(Integer.parseInt(mes[2].split("=")[1]));
                //单选和多选的归类
                question.setType(Question.SINGLE_SELECTION);
                if (answers.length > 1){
                    question.setType(Question.MULTI_SELECTION);
                }
                //获取题干和选项，默认一题目四选项 （后期可扩展）
                question.setTitle(questionReader.readLine());
                for (int i = 0; i < 4; i++) {
                    question.getOptions().add(questionReader.readLine());
                }

                //附上题目 id
                question.setId(ids++);
                //加入到集合中,不考虑题目重复
                questionList.get(question.getLevel()).add(question);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //从文件获取考试规则
    private void getRule(){
        String rulePath = config.getString("ExamRule");
        try {
            BufferedReader ruleReader = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(rulePath))));
            StringBuilder stringBuilder = new StringBuilder();
            String str;
            while ((str = ruleReader.readLine()) != null){
                stringBuilder.append(str + "\n");
            }
            rule = stringBuilder.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public String giveRule() {
        return rule;
    }


    public User getUserById(int idIn) {
        return userMap.get(idIn);
    }

    public ArrayList<QuestionInfo> getTestPaper() {
        //生成一份试卷,默认每个级别都有两题及以上题目
        int count = 1; //默认20道题
        Random ran = new Random();
        ArrayList<QuestionInfo> questionInfos = new ArrayList<>();
        for (int i = Question.LEVEL1; i <= questionList.size(); i++) {   //HashMap，所以得用key值找
            //每块随机拿题，并且打包成info然后返回, 已考虑题目重复
//            for (int j = 0; j < 2; j++) {
//                int index = ran.nextInt(questionList.get(i).size());
//                questionInfos.add(new QuestionInfo(count++, questionList.get(i).get(index)));
//            }
            int index1 = ran.nextInt(questionList.get(i).size());
            int index2;
            while (true){
                if ((index2 = ran.nextInt(questionList.get(i).size())) != index1) break;
            }
            questionInfos.add(new QuestionInfo(count++, questionList.get(i).get(index1)));
            questionInfos.add(new QuestionInfo(count++, questionList.get(i).get(index2)));
        }
        return questionInfos;
    }

    public ExamInfo getExamInfo() {
        //
        ExamInfo examInfo = new ExamInfo();
        examInfo.setQuestionCount(config.getInt("QuestionNumber"));
        examInfo.setTitle(config.getString("PaperTitle"));
        examInfo.setTimeLimit(config.getInt("TimeLimit"));

        return examInfo;
    }
}
